package com.chinaums.cfps.apps;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chinaums.cfps.apps.listener.MessageListener;
import com.chinaums.cfps.apps.utils.CfpsMQFactoryRcvQueueImpl;
import com.chinaums.cfps.apps.utils.CfpsRecvMQAppModel;


public class App 
{
	private final static Logger log = LoggerFactory.getLogger(App.class);
	
	public static String hostName;//MQ所在IP
	public static int port;//MQ监听所在端口
	public static String queueManager;//获取消息的MQ队列管理器
	public static String channel;//获取消息的MQ通道
	public static String queueName;//获取消息的队列名称
	public static String projectName;//项目名称
	public static String moduleName;//模块名称
	public static int lisRestartTimes;//监听重启次数
	public static int lisPauseTime;//监听重启间隔时间
	public static int moniPauseTime;//监控异常间隔时间
	
	//配置初始化
	static {
		Properties prop = new Properties();   
        InputStream in = App.class.
        		getClassLoader().getResourceAsStream("app.properties");
        
        try {   
            prop.load(in); 
        	App.hostName = prop.getProperty("rcvHost").trim();
        	App.port = Integer.parseInt(prop.getProperty("rcvPort").trim());
    		App.queueManager = prop.getProperty("rcvQueueManager").trim();
    		App.channel = prop.getProperty("rcvChannel").trim();
    		App.queueName = prop.getProperty("rcvQueueName").trim();
    		App.projectName = prop.getProperty("rcvProjectName").trim();
    		App.moduleName = prop.getProperty("rcvModuleName").trim();
    		App.lisRestartTimes = Integer.parseInt(prop.getProperty("lisRestartTimes").trim());
    		App.lisPauseTime = Integer.parseInt(prop.getProperty("lisPauseTime").trim());
    		App.moniPauseTime = Integer.parseInt(prop.getProperty("moniPauseTime").trim());
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {
        	if(in != null) {
        		try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
	}
	
    public static void main( String[] args )
    {
		int currentTimes = 0;

		MessageListener listener = new MessageListener();
		CfpsMQFactoryRcvQueueImpl mqFactory = new CfpsMQFactoryRcvQueueImpl(
				hostName, port, queueManager, channel, queueName, projectName,
				moduleName);
		CfpsRecvMQAppModel appModel = new CfpsRecvMQAppModel("App");

		appModel.setFactory(mqFactory);// 设置工厂
		appModel.setMqMessageListener(listener);// 设置消息监听器
		appModel.init();// 初始化
		
		while (true) {
			if (!listener.isOk()) {
				appModel.stop();// 停止监听
				
				if (currentTimes > lisRestartTimes) {
					break;
				}
				try {
					Thread.sleep(lisPauseTime);
				} catch (InterruptedException e) {
					log.error("" + e);
				}
				appModel.start();// 启动监听
				log.info("监听已启动");
				currentTimes++;
			}
			try {
				Thread.sleep(moniPauseTime);
			} catch (InterruptedException e) {
				log.error("" + e);
			}
		}	
    }
}
